﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ORS.OrderRobot.IOC;
using System.Collections.Concurrent;

namespace ORS.OrderRobot
{
    /// <summary>
    /// 默认的内存后台作业管理器。
    /// 在自身被创建时自动启动，在被销毁时自动停止。
    /// </summary>
    public class DefaultBackgroundJobManager : IBackgroundJobManager, ISingleton, IDisposable
    {
        private readonly ILogger<DefaultBackgroundJobManager> _logger;
        private readonly IServiceScopeFactory _serviceScopeFactory;
        
        private readonly ConcurrentQueue<JobExecutionInfo> _queue;
        private readonly SemaphoreSlim _queueSemaphore;
        private readonly Task _mainTask;
        private readonly CancellationTokenSource _cancellationTokenSource;

        public DefaultBackgroundJobManager(
            ILogger<DefaultBackgroundJobManager> logger,
            IServiceScopeFactory serviceScopeFactory)
        {
            _logger = logger;
            _serviceScopeFactory = serviceScopeFactory;
            
            _queue = new ConcurrentQueue<JobExecutionInfo>();
            _queueSemaphore = new SemaphoreSlim(0);
            
            _cancellationTokenSource = new CancellationTokenSource();
            _mainTask = Task.Run(ProcessQueueAsync);
            _logger.LogInformation("默认后台作业管理器已启动。");
        }

        public Task EnqueueAsync<TJob, TArgs>(TArgs args, int? delayMinute = null) where TJob : IBackgroundJob<TArgs>
        {
            if (_cancellationTokenSource.IsCancellationRequested)
            {
                return Task.CompletedTask; // Manager is shutting down, don't accept new jobs.
            }
            
            var jobInfo = new JobExecutionInfo(typeof(TJob), args);
            _queue.Enqueue(jobInfo);
            _queueSemaphore.Release();
            return Task.CompletedTask;
        }
        
        public void Dispose()
        {
            if (_cancellationTokenSource.IsCancellationRequested)
            {
                return;
            }

            _logger.LogInformation("正在停止默认后台作业管理器...");
            _cancellationTokenSource.Cancel();
            _queueSemaphore.Release(); // Unblock the waiting task

            try
            {
                // Block until the processing task has completely finished.
                _mainTask.Wait(TimeSpan.FromSeconds(5));
            }
            catch (OperationCanceledException) { /* Expected */ }
            catch (Exception ex)
            {
                _logger.LogError(ex, "停止后台作业时发生异常。");
            }
            finally
            {
                _cancellationTokenSource.Dispose();
            }
            _logger.LogInformation("默认后台作业管理器已停止。");
        }

        private async Task ProcessQueueAsync()
        {
            const int MaxRetryCount = 3;
            while (!_cancellationTokenSource.IsCancellationRequested)
            {
                try
                {
                    await _queueSemaphore.WaitAsync(_cancellationTokenSource.Token);
                }
                catch (OperationCanceledException)
                {
                    break; // Exit loop if cancellation is requested during wait.
                }

                if (_cancellationTokenSource.IsCancellationRequested)
                {
                    break;
                }

                if (_queue.TryDequeue(out var jobInfo))
                {
                    try
                    {
                        await ExecuteJobAsync(jobInfo);
                    }
                    catch (Exception ex)
                    {
                        if (jobInfo.RetryCount < MaxRetryCount)
                        {
                            jobInfo.RetryCount++;
                            _queue.Enqueue(jobInfo); // 重新加入队列尾部
                            _queueSemaphore.Release();
                            _logger.LogWarning(ex, "作业执行失败，已重试{RetryCount}次，将再次重试。作业类型: {JobType}", jobInfo.RetryCount, jobInfo.JobType.Name);
                        }
                        else
                        {
                            _logger.LogError(ex, "作业执行失败，已超过最大重试次数，作业被丢弃。作业类型: {JobType}", jobInfo.JobType.Name);
                        }
                    }
                }
            }
        }

        private async Task ExecuteJobAsync(JobExecutionInfo jobInfo)
        {
            using var scope = _serviceScopeFactory.CreateScope();
            var job = scope.ServiceProvider.GetService(jobInfo.JobType);
            if (job == null)
            {
                _logger.LogWarning("无法从依赖注入容器中解析作业。作业类型: {JobType}", jobInfo.JobType.Name);
                return;
            }

            var executeMethod = typeof(IBackgroundJob<>).MakeGenericType(jobInfo.Args.GetType()).GetMethod(nameof(IBackgroundJob<object>.ExecuteAsync));
            if (executeMethod == null)
            {
                _logger.LogWarning("无法在作业上找到 ExecuteAsync 方法。作业类型: {JobType}", jobInfo.JobType.Name);
                return;
            }

            await (Task)executeMethod.Invoke(job, new[] { jobInfo.Args });
        }

        /// <summary>
        /// 封装了执行一个作业所需的信息。
        /// </summary>
        private class JobExecutionInfo
        {
            public Type JobType { get; }
            public object Args { get; }
            public int RetryCount { get; set; }

            public JobExecutionInfo(Type jobType, object args)
            {
                JobType = jobType;
                Args = args;
                RetryCount = 0;
            }
        }
    }
}
